package com.hsmw.api.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hsmw.api.mapper.HsmwAuditMapper;
import com.hsmw.api.mapper.HsmwDictDataMapper;
import com.hsmw.api.mapper.HsmwUserDriverMapper;
import com.hsmw.api.mapper.HsmwUserMapper;
import com.hsmw.common.base.BaseService;
import com.htn.common.core.constant.AuditStatusEnum;
import com.htn.common.core.constant.UserTypeEnum;
import com.hsmw.domain.HsmwDictData;
import com.hsmw.domain.HsmwUserDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class HsmwDictDataService extends BaseService<HsmwDictDataMapper, HsmwDictData> {

	@Autowired
	private HsmwDictDataMapper hsmwDictDataMapper;

	@Autowired
	private HsmwUserMapper hsmwUserMapper;

	@Autowired
	private HsmwAuditMapper hsmwAuditMapper;

	@Autowired
	private HsmwUserDriverMapper hsmwUserDriverMapper;

	@Autowired
	private HsmwVehicleService hsmwVehicleService;

	public List<HsmwDictData> getOrderDicDate(LambdaQueryWrapper<HsmwDictData> lambdaQueryWrapper) {
		return hsmwDictDataMapper.selectList(lambdaQueryWrapper);

	}


	public List<HsmwDictData> getDictDataByParent(String dictLabel) {
		HsmwDictData hsmwDictData = hsmwDictDataMapper.selectOne(Wrappers.lambdaQuery(HsmwDictData.class).eq(HsmwDictData::getDictLabel, dictLabel));
		List<HsmwDictData> hsmwDictDataList = hsmwDictDataMapper.selectList(Wrappers.lambdaQuery(HsmwDictData.class).eq(HsmwDictData::getDictType, hsmwDictData.getParentDictType()));
		return hsmwDictDataList;
	}

	@Transactional
    public boolean unbindDriverUserAndVehicle(String userId) {

		boolean auditSuc = hsmwAuditMapper.updateAuditStatusByUserId(userId, AuditStatusEnum.FAILED.getName());

		boolean userSuc = hsmwUserMapper.updateUserTypeByUserId(userId, UserTypeEnum.VISITOR.getValue());

		boolean driverSuc = hsmwUserDriverMapper.deleteUserDriverById(userId);
		if(auditSuc && userSuc && driverSuc){
			return true;
		}
			return false;
	}

	@Transactional
	public boolean delDriverById(String driverId) {

		List<HsmwUserDriver> hsmwUserDrivers = hsmwUserDriverMapper.selectList(new LambdaQueryWrapper<HsmwUserDriver>().eq(HsmwUserDriver::getVehicleId, driverId));
		for (HsmwUserDriver hsmwUserDriver : hsmwUserDrivers) {
			this.unbindDriverUserAndVehicle(hsmwUserDriver.getUserId());
		}
		boolean remove = hsmwVehicleService.removeById(driverId);

		if(remove){
			return true;
		}
		return false;
	}
}
